﻿using System;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using ComicReader.Model;
using ICSharpCode.SharpZipLib.Zip;

namespace ComicReader.Helpers
{
    public class PageDataToImageSourceConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter,
                              CultureInfo culture)
        {

            if (value is PageData)
            {
                return (value as PageData).Image;
            }

            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter,
                                  CultureInfo culture)
        {
            throw new NotSupportedException();
        }


        public MemoryStream GetMemoryStream(Stream s)
        {
            var ba = new byte[4096];
            var ms = new MemoryStream();
            var numRead = s.Read(ba, 0, ba.Length);
            while (numRead > 0)
            {
                ms.Write(ba, 0, numRead);
                numRead = s.Read(ba, 0, ba.Length);
            }
            ms.Position = 0;
            return ms;
        }

        public BitmapImage GetBitmapImage(ZipEntry zipEntry)
        {
            var stream = App.ZipFile.GetInputStream(zipEntry);
            var positiom = stream.Position;
            var length = stream.Length;

            var memoryStream = GetMemoryStream(stream);
            var bitmap = new Bitmap(memoryStream); //make sure its valid
            memoryStream.Position = 0;

            var bitmapImage = new BitmapImage();
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = memoryStream; //could exception
            bitmapImage.EndInit();

            bitmap.Dispose();

            return bitmapImage;
        }
    }
}